﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Mapper;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Controllers
{
    public class MyTestController : Controller
    {

        /// <summary>
        /// 自定义表单
        /// </summary>
        /// <returns></returns>
        public IActionResult MyCustomForm()
        {
            var instanceid = this.Request.Querys("instanceid");

            DataTable dt = new DataTable();

            if (!instanceid.IsNullOrWhiteSpace())
            {
                using(var db=new DataContext())
                {
                    dt = db.GetDataTable("select * from rf_test where id={0}",instanceid);
                }
            }

            return View(dt);
        }


        /// <summary>
        /// 保存自定义表单
        /// </summary>
        /// <returns></returns>
        public string SaveMyCustomForm()
        {
            string instanceid = Request.Querys("instanceid");
            string title = Request.Forms("Title");
            string Contents = Request.Forms("Contents");
            string sql = instanceid.IsNullOrWhiteSpace() ?
                "insert into RF_Test(Id,F1,F2) values({0},{1},{2})" :
                "update rf_test set f1={0},f2={1} where id={2}";
            Guid id = Guid.NewGuid();
            using (var db = new DataContext())
            {
                if (instanceid.IsNullOrWhiteSpace())
                {
                    db.Execute(sql, id, title, Contents);
                }
                else
                {
                    db.Execute(sql, title, Contents, instanceid);
                }
                db.SaveChanges();
            }
            Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
            {
                { "success", 1 },
                { "message", "保存成功" },
                { "instanceid", id.ToString() },
                { "title", title }
            };
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

    }
}